#include "sendConfigRequest.h"
#include "curlRequestUtil.h"
#include <cjson/cJSON.h>
#include <stdio.h>
#include <glib.h>

size_t configWriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    // 这里可以处理获取到的数据，比如存储到文件或者其他操作
    char * result = (char *)contents;
    
    // 利用cJSONqu解析json字符串
    cJSON* root = cJSON_Parse(result);  // 将json字符串转成json对象
    if(root != NULL)
    {
        cJSON* successJson = cJSON_GetObjectItemCaseSensitive(root,"success");
        cJSON* codeJson = cJSON_GetObjectItemCaseSensitive(root,"code");
        cJSON* messageJson = cJSON_GetObjectItemCaseSensitive(root,"message");

        if(successJson->valueint == 1 && codeJson->valueint == 200)
        {
            printf("广告机信息注册成功！\n");
        }
        else{
            printf("广告机信息注册失败!失败:%s\n",messageJson->valuestring);
        }
    }

    printf("%s\n",result);
    return realsize;
}

void sendConfigRequest(char** gatewayIp,char* sn){
    GKeyFile *file = g_key_file_new();
    g_key_file_load_from_file(file,"../config/config.ini",G_KEY_FILE_NONE,NULL);
    gchar* path = g_key_file_get_string(file,"config","deviceInfoPath",NULL);


    GKeyFile *keyFile = g_key_file_new();
    g_key_file_load_from_file(keyFile,path,G_KEY_FILE_NONE,NULL);
    *gatewayIp = g_key_file_get_string(keyFile,"config","gatewayIp",NULL);
    char* location = g_key_file_get_string(keyFile,"config","location",NULL);

    g_key_file_free(keyFile);
    g_key_file_free(file);

    char* urlFormatStr="http://%s/config.json?sn=%s&location=%s";
    char* url=(char*)calloc(1,100);

    sprintf(url,urlFormatStr,*gatewayIp,sn,location);
    printf("config request url:%s\n",url);
    sendGetRequest(url,configWriteCallback);
}